$(function(){
    var MASK = '<div id="oldExamPlanMask" class="mask" style="display: none;"></div>';
    var DIALOG_HTML = '<div id="oldExamPlan" class="dialog-choose-exam-outer oldExamPlan" style="display: none;position:absolute;">' +
                            '<div class="dialog-choose-exam">' +
                                '<div class="dialog-head" style="background-color:#E25C00;"><div class="dialog-title" style="padding-top:12px;" ><span style="color:white;">考试计划</span></div></div>' +
                                '<div name="oldExamPlanContent"></div>' +
                            '</div>' +
                        '</div>';
    var SELECT_PROVINCE_HTML = '<div class="dialog-oldExamPlan-province">' +
                                    '<div>' +
                                        '<span style="color:#fa6900">重要！</span>' +
                                        '<span>请选择报考省份，系统将根据报考省份为你生成考试计划</span>' +
                                    '</div>' +
                                    '<div style="margin-top: 15px;">' +
                                        '<select name="provinceSelect"></select>' +
                                    '</div>' +
                                    '<div name="submit" style="margin-top: 15px;" class="partPop_but footer-btn submit-btn">确认</div>' +
                                '</div>';
    var SHOW_EXAMPLAN_HTML = '<div class="dialog-oldExamPlan-show">' +
                                    '<div class="dialog-oldExamPlan-show-title"><span style="color: #fa6900">重要：</span><span>请确认201710考期考试安排！</span></div>' + 
                                    '<div class="dialog-oldExamPlan-show-wrap">' +
                                        '<div class="dialog-oldExamPlan-show-bar">' + 
                                            '<div class="dialog-oldExamPlan-show-province">报考省份：<span style="color: #fa6900"></span></div>' +
                                            '<div class="dialog-oldExamPlan-show-season">当前学期：<span style="color: #fa6900"></span></div>' +
                                        '</div>' +
                                        '<div class="dialog-oldExamPlan-show-exam">' +
                                            '<table>' +
                                                '<tbody>' +
                                                    '<tr><td width="20%" height="30px">考试日期</td><td width="40%" height="30px">上午</td><td width="40%" height="30px">下午</td></tr>' +
                                                '</tbody>' +
                                            '</table>' +
                                        '</div>' +
                                        '<div style="margin-top: 15px;">' +
                                            '<span>变更考试安排会影响直播课表，且每个考期只有一次变更的机会，请慎重修改</span>' +
                                            '<br>' +
                                            '<span>如上述报考省份有误，你可先确认考试安排，之后联系班主任修改</span>' +
                                        '</div>' +
                                        '<div class="dialog-oldExamPlan-show-buttonbar">' +
                                            '<div style="float: left; margin-right: 10px; background: white; border: 1px solid #E25C00; color: #E25C00;" class="partPop_but footer-btn" name="change">变更考试安排</div>' +
                                            '<div style="float: left;" class="partPop_but footer-btn" name="confirmOriginalPlan">确认考试安排</div>' +
                                        '</div>' +
                                    '</div>' +
                                '</div>';
    var CHANGE_EXAMPLAN_HTML = '<div class="dialog-oldExamPlan-change">' +
                                    '<div class="dialog-oldExamPlan-change-title">变更考试计划</div>' +
                                    '<div class="dialog-oldExamPlan-change-exam">' +
                                        '<table>' +
                                            '<tbody>' +
                                                '<tr><td width="20%" height="30px">考试日期</td><td width="40%" height="30px">上午</td><td width="40%" height="30px">下午</td></tr>' +
                                            '</tbody>' +
                                        '</table>' +
                                    '</div>' +
                                    '<div class="dialog-oldExamPlan-change-buttonbar">' +
                                        '<div style="float: left; margin-right: 10px; background: white; border: 1px solid #E25C00; color: #E25C00;" class="partPop_but footer-btn" name="return">返回不改了</div>' +
                                        '<div style="float: left;" class="partPop_but footer-btn" name="confirmNewPlan">确认考试安排</div>' +
                                    '</div>' +
                                '</div>';
    var LOADING_HTML = '<div class="loading">数据处理中，请等待...</div>'

    var OldStudentExamPlan = function(options) {
        this.options = options || {}
        this.examPlanId = -1;
        this.projectSecondId = -1;
        this.ordDetailId = -1;
        this.init();
    }

    OldStudentExamPlan.prototype.init = function() {
        this.$el = $('<div></div>');
        this.initEvents();
        this.renderProvice();
    };

    OldStudentExamPlan.prototype.initEvents = function() {
        var that = this;
        //绑定选择省份的事件
        this.$el.on('change', 'select[name="provinceSelect"]', function(e) {
            if(e.target) {
                var $target = $(e.target)
                if($target.val() > -1) {
                    that.$el.find('div[name="submit"]').removeClass('submit-btn');
                } else {
                    that.$el.find('div[name="submit"]').addClass('submit-btn');
                }
            }
        })
        //绑定提交省份的事件
        this.$el.on('click', 'div[name="submit"]', function(e) {
            if(e.target) {
                var $target = $(e.target);
                var province = that.$el.find('select[name="provinceSelect"]').val()
                if(province > -1) {
                    that.$el.empty().append(LOADING_HTML);
                    $.ajax({
                        url: "new_pt_uc/exam_plan/saveExamProvince.action",
                        type: "post",
                        data: {
                            provinceId: province
                        },
                        cache: false,
                        dataType: 'json',
                        success: function(rs){
                            if(rs.flag == 1) {
                                that.renderExamPlanShow();
                            } else {
                                alert('抱歉，系统没有找到对应的考试计划，请联系您的班主任！')
                                //失败后，干掉loading页面，重新选择省份
                                that.destroy();
                            }
                        }
                    });
                }
            }
        })

        //绑定不修改考试计划事件
        this.$el.on('click', 'div[name="confirmOriginalPlan"]', function() {
            if(confirm('确认后，每个考期的考试安排只能修改一次，如需再次修改需要联系班主任')) {
                $.ajax({
                    url: "new_pt_uc/exam_plan/confirmExamPlan.action",
                    type: "post",
                    cache: false,
                    data: {
                        examPlanId: that.examPlanId,
                        ordDetailId: that.ordDetailId
                    },
                    dataType: 'json',
                    success: function(rs){
                        if(rs.flag == 1) {
                            that.destroy();
                            // window.location.href = "http://yi.sunlands.com/ent-portal-war/new_pt_uc/exam_plan/planHome.action?actionFlag=examPlan"
                            window.location.href = "http://172.16.117.206:7162/ent-portal-war/new_pt_uc/exam_plan/planHome.action?actionFlag=examPlan"
                        } else {
                            alert('抱歉，系统没有找到对应的考试计划，请联系您的班主任！')
                            that.destroy();
                        }
                        
                    }
                });
            }
            
        })

        //绑定修改考试计划事件
        this.$el.on('click', 'div[name="change"]', function() {
            that.renderExamPlanChange();
        })

        //修改考试计划绑定事件
        this.$el.on('click', 'div[name="confirmNewPlan"]', function() {
            if(confirm('确认后，每个考期的考试安排只能修改一次，如需再次修改需要联系班主任')) {
                var baseInfoIds = [];
                var selectedCheckboxes = $(that.$el.find('.dialog-oldExamPlan-change-exam')).find('input[type=checkbox]:checked')
                for (var i = 0; i < selectedCheckboxes.length; i++) {
                    baseInfoIds[baseInfoIds.length] = $(selectedCheckboxes[i]).attr('baseInfoId')
                }
                $.ajax({
                    url: "new_pt_uc/exam_plan/setUserExamArrange.action",
                    type: "post",
                    cache: false,
                    data: {
                        examPlanId: that.examPlanId,
                        projectSecondId: that.projectSecondId,
                        ordDetailId: that.ordDetailId,
                        baseInfoIds: baseInfoIds.join(','),
                        currentTerm: that.currentTerm
                    },
                    dataType: 'json',
                    success: function(rs){
                        if(rs.flag == 1) {
                            that.destroy();
                            // window.location.href = "http://yi.sunlands.com/ent-portal-war/new_pt_uc/exam_plan/planHome.action?actionFlag=examPlan"
                            window.location.href = "http://172.16.117.206:7162/ent-portal-war/new_pt_uc/exam_plan/planHome.action?actionFlag=examPlan"
                        } else {
                            alert('抱歉，系统没有找到对应的考试计划，请联系您的班主任！')
                            that.destroy();
                        }
                        
                    }
                });
            }
        })

        //从修改考试计划返回到查看考试计划
        this.$el.on('click', 'div[name="return"]', function() {
            if(confirm('确认放弃本次修改内容？')) {
                that.renderExamPlanShow();
            }
        })

        //选择考试项目的checkbox的事件
        this.$el.on('click', $(that.$el.find('.dialog-oldExamPlan-change-exam')).find('input[type=checkbox]'), function(e){
            if(e.target) {
                var $target = $(e.target);
                var isChecked = $target.prop('checked')
                if(isChecked) {
                    that.$el.find('input[name="' + $target.attr('name') + '"]').prop('checked', !isChecked)
                    $target.prop('checked', isChecked)    
                }
            }
        })
    };

    OldStudentExamPlan.prototype.renderProvice = function() {
        var that = this;
        $.ajax({
            url: "new_pt_uc/exam_plan/checkExamProvince.action",
            type: "post",
            cache: false,
            dataType: 'json',
            success: function(rs){
                if(rs.flag == 1) {
                    that.projectSecondId = rs.data.projectSecondId;
                    that.ordDetailId = rs.data.ordDetailId;
                    if(rs.data.enrollProvince==1){
                        //弹出填写报考省份弹窗
                        that.$el.empty().append(SELECT_PROVINCE_HTML);
                        provinceList = rs.data.provinceList;
                        that.$el.find('select[name="provinceSelect"]').empty().append('<option value=-1>请选择省份</option>')
                        for (var i = 0; i < provinceList.length; i++) {
                            that.$el.find('select[name="provinceSelect"]').append('<option value=' + provinceList[i].id + '>' + provinceList[i].name + '</option>')
                        }
                    } else if(rs.data.changeExamplan==1){
                        //弹出填写考试计划弹窗
                        that.renderExamPlanShow();
                    }
                } else {
                    alert('抱歉，系统没有找到对应的考试计划，请联系您的班主任！')
                    that.destroy();
                }
                
            }
        });
    }

    OldStudentExamPlan.prototype.renderExamPlanShow = function() {
        var that = this;
        $.ajax({
            url: "new_pt_uc/exam_plan/queryExamPlanJSON.action",
            type: "post",
            cache: false,
            data: {
                projectSecondId: that.projectSecondId,
                ordDetailId: that.ordDetailId
            },
            dataType: 'json',
            success: function(rs){
                if(rs.flag == 1) {
                    that.$el.empty().append(SHOW_EXAMPLAN_HTML);
                    var data = rs.data;
                    that.examPlanId = data.examPlanId;
                    that.currentTerm = data.currentTerm;
                    that.$el.find('.dialog-oldExamPlan-show-province').find('span').html(data.areaName)
                    that.$el.find('.dialog-oldExamPlan-show-season').find('span').html(data.currentTermName)
                    //删除除表头外的其他行
                    var $table = that.$el.find('.dialog-oldExamPlan-show-exam').find('table');
                    $table.find('tr:gt(0)').remove();
                    for (var i = 0; i < data.examArranges.length; i++) {
                        var exam = data.examArranges[i];
                        var $tr = $('<tr></tr>');
                        $tr.append($('<td>' + exam.date + '</td><td>' + (exam.amExam.name || '') + '</td><td>' + (exam.pmExam.name || '') + '</td>'))
                        $table.append($tr);
                    }
                } else {
                    alert('抱歉，系统没有找到对应的考试计划，请联系您的班主任！')
                    that.destroy();
                }
                
            }
        });
    };

    OldStudentExamPlan.prototype.renderExamPlanChange = function() {
        var that = this;
        $.ajax({
            url: "new_pt_uc/exam_plan/getExamCourseByExamPlanId.action",
            type: "post",
            cache: false,
            data: {
                examPlanId: this.examPlanId,
                projectSecondId: this.projectSecondId,
                ordDetailId: this.ordDetailId
            },
            dataType: 'json',
            success: function(rs){
                if(rs.flag == 1) {
                    that.$el.empty().append(CHANGE_EXAMPLAN_HTML)
                    var data = rs.data;
                    //删除除表头外的其他行
                    var $table = that.$el.find('.dialog-oldExamPlan-change-exam').find('table');
                    $table.find('tr:gt(0)').remove();
                    for(var date in data) {
                        if(data.hasOwnProperty(date)) {
                            var $tr = $('<tr></tr>');
                            var amExams = data[date].am;
                            var pmExams = data[date].pm;
                            $tr.append($('<td>' + date + '</td>'));
                            var $amTd = $('<td style="text-align:left"></td>');
                            for (var i = 0; i < amExams.length; i++) {
                                $amTd.append('<div><input type="checkbox" baseInfoId="' + amExams[i].baseInfoId + '" ' + (amExams[i].selected ? 'checked' : '') + ' name="amExams_' + date + '"/>' + amExams[i].name + '</div>');

                            }
                            var $pmTd = $('<td style="text-align:left"></td>');
                            for (var i = 0; i < pmExams.length; i++) {
                                $pmTd.append('<div style="margin-top: 5px;"><input type="checkbox" baseInfoId="' + pmExams[i].baseInfoId + '" ' + (pmExams[i].selected ? 'checked' : '') + ' name="pmExams_' + date + '"/>' + pmExams[i].name + '</div>');
                            }
                            $tr.append($amTd);
                            $tr.append($pmTd);
                            $table.append($tr);
                        }
                    }
                } else {
                    alert('抱歉，系统没有找到对应的考试计划，请联系您的班主任！')
                    that.destroy();
                }
                
            }
        });
    };

    OldStudentExamPlan.prototype.showDialog = function() {
        this.$mask = $(MASK).appendTo('body');
        this.$dialog = $(DIALOG_HTML).appendTo('body');
        this.$dialog.find('div[name="oldExamPlanContent"]').empty().append(this.$el)
        this.$mask.show();
        this.$dialog.show();
    };

    OldStudentExamPlan.prototype.destroy = function() {
        if(this.$mask) {
            this.$mask.remove();
        }
        if(this.$dialog) {
            this.$dialog.remove();
        }
    }

    window.OldStudentExamPlan = OldStudentExamPlan;

})